# %%
import os
import traceback
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from asammdf import MDF
import scipy
from pylab import mpl
def inca(mdf_file_path,a):
    def OutlierDetection(df):
        ll=[]
        # 计算均值
        mean = df.mean()
        # 计算标准差
        std = df.std()
        # 输出均值和标准差   
        # print('均值为：%.3f，标准差为：%.3f，均值加3倍标准差为：%.3f，均值加3倍标准差为：%.3f' % (mean, std, mean+3*std, mean-3*std))
        # 定义3σ法则识别异常值
        # 识别异常值        
        error = df[np.abs(df - mean) > 3 * std]
        # 剔除异常值，保留正常的数据
        data_c = df[np.abs(df - mean) <= 3 * std]
        for j in range(len(data_c)-1):
            if data_c.index[j+1]-data_c.index[j]>0.007:
                s=j+1
                o=j
                while data_c.iloc[s]<mean:                  
                    ll.append(data_c.index[s])
                    s=s+1
                while data_c.iloc[o]<mean:
                    ll.append(data_c.index[o])
                    o=o-1
        data_cc=data_c.drop(ll,axis=0)
        return data_cc # 150.953408    0.0
    
    def Detection(df):
        ll=[]
        for j in range(len(df)-1):
            if df.index[j+1]-df.index[j]>52:
                ll=df.index[j+1:].tolist()
                break
        df_c=df.drop(ll,axis=0)
        return df_c # 150.953408    0.0
    
    try:
        mpl.rcParams['font.sans-serif'] = ['SimHei']
        path = os.path.basename(mdf_file_path)# 返回路径最后的文件名。
        mdf = MDF(mdf_file_path)
        chn_db = mdf.channels_db
        if 'Per' in chn_db.keys() :
            dfx=mdf.get_group(int(str(chn_db['Per'][0]).split("(")[1].split(",")[0]))
            dfx.columns=dfx.columns.str.split("\\\\").str[0]
        # if 'Vafr1' in chn_db.keys() :
        #     dfc=mdf.get_group(int(str(chn_db['Vafr1'][0]).split("(")[1].split(",")[0]))
        #     dfc.columns=dfc.columns.str.split("\\\\").str[0]
        if a==1:
            try:
                # 判断缸温在75℃之后        
                pet1=dfx['Pet']*-1# 翻转，求波谷
                peakspern, _ = scipy.signal.find_peaks(pet1, distance=108000)            
                pet=dfx['Pet'].iloc[int(peakspern[0]):]# 缸温
                pexcurrent=dfx['Pexcurrent'].iloc[int(peakspern[0]):]# 电流
                pjtext=dfx['Pjtext'].iloc[int(peakspern[0]):]# 喷油量
                ptd=dfx['Ptd'].iloc[int(peakspern[0]):]# 节气门开度
                piapm=dfx['Piapm'].iloc[int(peakspern[0]):]# 进气压力
                # 空燃比
                # if 'dfc' in locals() or 'dfc' in globals():
                #     vafr1=dfc['Vafr1'].iloc[int(peakspern[0]):]
                #     vafr2=dfc['Vafr2'].iloc[int(peakspern[0]):]
                #     if vafr1.mean()<=15.5:
                #         n=1
                #     if vafr2.mean()<=15.5:
                #         n=2
                pafr=dfx['Pafr'].iloc[int(peakspern[0]):]
                if pafr.mean()<=15.5:
                    n=0 
                # 筛选后的数据
                data = [ [] for _ in range(9) ]
                datass = [ pd.Series() for _ in range(9) ]            
                df1 = [ pd.Series() for _ in range(9) ]
                df2 = [ pd.Series() for _ in range(9) ]
                df3 = [ pd.Series() for _ in range(9) ]
                df4 = [ pd.Series() for _ in range(9) ]            
                # 筛选前的数据
                pexcurrentt = [ [] for _ in range(5) ]            
                pexcurrents = [ pd.Series() for _ in range(9) ]
                pjtexts = [ pd.Series() for _ in range(9) ]
                ptds = [ pd.Series() for _ in range(9) ]
                piapms = [ pd.Series() for _ in range(9) ]                    
                pexcurrentresult = [ pd.Series() for _ in range(9) ]
                pjtextresult = [ pd.Series() for _ in range(9) ]
                ptdresult = [ pd.Series() for _ in range(9) ]
                piapmresult = [ pd.Series() for _ in range(9) ]
                # 按照功率点分割时间
                for i in range(len(pexcurrent.index)):
                    if (pet.iloc[i]>75) and (pexcurrent.iloc[i]<5):
                        if pexcurrent.iloc[i]==0:
                            pexcurrentt[0].append(i)
                    if (pet.iloc[i]>75) and (pexcurrent.iloc[i]<10) and (pexcurrent.iloc[i]>5):
                        pexcurrentt[1].append(i)
                    if (pet.iloc[i]>75) and (pexcurrent.iloc[i]<20) and (pexcurrent.iloc[i]>15):
                        pexcurrentt[2].append(i)
                    if (pet.iloc[i]>75) and (pexcurrent.iloc[i]<30) and (pexcurrent.iloc[i]>20):
                        pexcurrentt[3].append(i)
                    if (pet.iloc[i]>75) and (pexcurrent.iloc[i]>30):
                        pexcurrentt[4].append(i)
                for i in range(4):
                    for j in range(len(pexcurrentt[i])-1):
                        if pexcurrent.index[pexcurrentt[i][j+1]]-pexcurrent.index[pexcurrentt[i][j]]>(7-i*2)*52:
                            pexcurrents[i]=pexcurrent.iloc[pexcurrentt[i][4000:j+1]]
                            pexcurrents[8-i]=pexcurrent.iloc[pexcurrentt[i][j+4001:]]
                            pjtexts[i]=pjtext.iloc[pexcurrentt[i][4000:j+1]]
                            pjtexts[8-i]=pjtext.iloc[pexcurrentt[i][j+4001:]]
                            ptds[i]=ptd.iloc[pexcurrentt[i][4000:j+1]]
                            ptds[8-i]=ptd.iloc[pexcurrentt[i][j+4001:]]
                            piapms[i]=piapm.iloc[pexcurrentt[i][4000:j+1]]
                            piapms[8-i]=piapm.iloc[pexcurrentt[i][j+4001:]]
                            break
                pexcurrents[4]=pexcurrent.iloc[pexcurrentt[4][4000:]]
                pjtexts[4]=pjtext.iloc[pexcurrentt[4][4000:]]
                ptds[4]=ptd.iloc[pexcurrentt[4][4000:]]
                piapms[4]=piapm.iloc[pexcurrentt[4][4000:]]
                # # plt.subplot(411)
                # plt.title("电流")
                # plt.plot(pexcurrent)
                for i in range(len(pexcurrents)):
                    # plt.plot(pexcurrents[i],'o')
                    pexcurrentresult[i]=OutlierDetection(pexcurrents[i])
                    # plt.plot(pexcurrentresult[i],'p')
                # plt.subplot(412)
                # plt.title("喷油量")
                # plt.plot(pjtext)
                for i in range(len(pjtexts)):
                    # plt.plot(pjtexts[i],'o')
                    pjtextresult[i]=OutlierDetection(pjtexts[i])
                    # plt.plot(pjtextresult[i],'p')
                # plt.subplot(413)
                # plt.title("节气门开度")
                # plt.plot(ptd)
                for i in range(len(ptds)):
                    # plt.plot(ptds[i],'o')
                    ptdresult[i]=OutlierDetection(ptds[i])
                    # plt.plot(ptdresult[i],'p')
                # plt.subplot(414)
                # plt.title("进气压力")
                # plt.plot(piapm)
                for i in range(len(piapms)):
                    # plt.plot(piapms[i],'o')
                    piapmresult[i]=OutlierDetection(piapms[i])
                    # plt.plot(piapmresult[i],'p')
                for i in range(len(pexcurrents)):
                    for j in range(len(pexcurrent.index)):
                        if pexcurrent.index[j] in pexcurrentresult[i].index and pexcurrent.index[j] in pjtextresult[i].index and pexcurrent.index[j] in ptdresult[i].index and pexcurrent.index[j] in piapmresult[i].index:
                            data[i].append(j)
                l10=['分析'+path+'文件的节气门开度数据：']
                l20=['分析'+path+'文件的进气压力数据：']
                l30=['分析'+path+'文件的喷油量数据：']
                l40=['分析'+path+'文件的空燃比数据：']
                ps=['空载时','25%功率点时','50%功率点时','75%功率点时','100%功率点时','75%功率点时','50%功率点时','25%功率点时','空载时']
                for i in range(len(pexcurrents)):
                    datass[i]=pexcurrent.iloc[data[i]]
                    plt.subplot(311)
                    plt.title("电流")
                    plt.plot(pexcurrent)
                    plt.plot(datass[i],'s')
                    df1[i]=ptd.iloc[data[i]]
                    plt.subplot(323)
                    plt.title("节气门开度")
                    plt.plot(ptd)
                    plt.plot(df1[i],'s')
                    df2[i]=piapm.iloc[data[i]]
                    plt.subplot(324)
                    plt.title("进气压力")
                    plt.plot(piapm)
                    plt.plot(df2[i],'s')
                    df3[i]=pjtext.iloc[data[i]]
                    plt.subplot(325)
                    plt.title("喷油量")
                    plt.plot(pjtext)
                    plt.plot(df3[i],'s')
                    if n==0:
                        df4[i]=pafr.iloc[data[i]]
                        p='Pafr'
                        plt.subplot(326)
                        plt.title("空燃比")
                        plt.plot(pafr)
                        plt.plot(df4[i],'s')
                    # if n==1:                        
                    #     df4[i]=vafr1.iloc[data[i]]
                    #     p='Vafr1'
                    #     plt.subplot(326)
                    #     plt.title("空燃比")
                    #     plt.plot(vafr1)
                    #     plt.plot(df4[i],'s')
                    # if n==2:
                    #     df4[i]=vafr2.iloc[data[i]]
                    #     p='Vafr2'
                    #     plt.subplot(326)
                    #     plt.title("空燃比")
                    #     plt.plot(vafr2)
                    #     plt.plot(df4[i],'s')
                    l1='{0}节气门开度Ptd（°）的范围是{1}~{2}，平均值是{3}，标准差是{4}'.format(ps[i],df1[i].min().round(2),df1[i].max().round(2),df1[i].mean().round(2),df1[i].std(ddof=0).round(2))
                    l10.append(l1)
                    l2='{0}进气压力Piapm（kpa）的范围是{1}~{2}，平均值是{3}，标准差是{4}'.format(ps[i],df2[i].min().round(2),df2[i].max().round(2),df2[i].mean().round(2),df2[i].std(ddof=0).round(2))
                    l20.append(l2)
                    l3='{0}喷油量Pjtext（ms）的范围是{1}~{2}，平均值是{3}，标准差是{4}'.format(ps[i],df3[i].min().round(2),df3[i].max().round(2),df3[i].mean().round(2),df3[i].std(ddof=0).round(2))
                    l30.append(l3)
                    l4='{0}空燃比{1}（La）的范围是{2}~{3}，平均值是{4}，范围差是{5}，标准差是{6}'.format(ps[i],p,df4[i].min().round(2),df4[i].max().round(2),df4[i].mean().round(2),(df4[i].max().round(2)-df4[i].min().round(2)).round(2),df4[i].std(ddof=0).round(2))
                    l40.append(l4)
            except Exception as e:
                print('\n','>>>' * 20)
                print(traceback.format_exc())
                pass
            plt.tight_layout()
            plt.show()
            return l10,l20,l30,l40
        if a==2:
            try:
                # 1stn到最后
                p1cstn=dfx['P1cstn']# 1stn
                p2cstn=dfx['P2cstn']# 2stn
                for i in range(len(p2cstn)):
                    if p2cstn.iloc[i]==1:
                        while p1cstn.iloc[i]==1:
                            i=i-1
                        pet1stn=dfx['Pet'].iloc[i+1:]# 缸温
                        piat1stn=dfx['Piat'].iloc[i+1:]# 进气温度
                        pbtv1stn=dfx['Pbtv'].iloc[i+1:]# 电池电压
                        pexcurrent=dfx['Pexcurrent'].iloc[i+1:]# 电流
                        break
                # 筛选前的数据
                pexcurrentt = [ [] for _ in range(5) ]
                pexcurrents = [ pd.Series() for _ in range(9) ]
                piat1stns = [ pd.Series() for _ in range(9) ]
                pet1stns = [ pd.Series() for _ in range(9) ]
                pbtv1stns = [ pd.Series() for _ in range(9) ]
                piat1stnresult = [ [ pd.Series() for _ in range(5) ] for _ in range(9) ]
                pet1stnresult = [ [ pd.Series() for _ in range(5) ] for _ in range(9) ]
                pbtv1stnresult = [ [ pd.Series() for _ in range(5) ] for _ in range(9) ]
                
                # 按照功率点分割时间
                for i in range(len(pexcurrent.index)):
                    if pexcurrent.iloc[i]==0:
                        pexcurrentt[0].append(i)
                    if (pexcurrent.iloc[i]<10) and (pexcurrent.iloc[i]>5):
                        pexcurrentt[1].append(i)
                    if (pexcurrent.iloc[i]<20) and (pexcurrent.iloc[i]>15):
                        pexcurrentt[2].append(i)
                    if (pexcurrent.iloc[i]<30) and (pexcurrent.iloc[i]>20):
                        pexcurrentt[3].append(i)
                    if (pexcurrent.iloc[i]>30):
                        pexcurrentt[4].append(i)
                for i in range(4):
                    for j in range(len(pexcurrentt[i])-1):
                        if pexcurrent.index[pexcurrentt[i][j+1]]-pexcurrent.index[pexcurrentt[i][j]]>(7-i*2)*52: 
                            pexcurrents[i]=pexcurrent.iloc[pexcurrentt[i][0:j+1]]
                            pexcurrents[8-i]=pexcurrent.iloc[pexcurrentt[i][j+1:]]
                            piat1stns[i]=piat1stn.iloc[pexcurrentt[i][0:j+1]]
                            piat1stns[8-i]=piat1stn.iloc[pexcurrentt[i][j+1:]]
                            pet1stns[i]=pet1stn.iloc[pexcurrentt[i][0:j+1]]
                            pet1stns[8-i]=pet1stn.iloc[pexcurrentt[i][j+1:]]
                            pbtv1stns[i]=pbtv1stn.iloc[pexcurrentt[i][0:j+1]]
                            pbtv1stns[8-i]=pbtv1stn.iloc[pexcurrentt[i][j+1:]]
                            break
                pexcurrents[4]=pexcurrent.iloc[pexcurrentt[4]]
                piat1stns[4]=piat1stn.iloc[pexcurrentt[4]]
                pet1stns[4]=pet1stn.iloc[pexcurrentt[4]]
                pbtv1stns[4]=pbtv1stn.iloc[pexcurrentt[4]]
                for i in range(len(pexcurrents)):
                    pexcurrents[i]=Detection(pexcurrents[i])
                    pexcurrents[i]=pexcurrent.loc[pexcurrents[i].index[0]:pexcurrents[i].index[-1]]
                for i in range(len(piat1stns)):
                    piat1stns[i]=Detection(piat1stns[i])
                    piat1stns[i]=piat1stn.loc[piat1stns[i].index[0]:piat1stns[i].index[-1]]
                for i in range(len(pet1stns)):
                    pet1stns[i]=Detection(pet1stns[i])
                    pet1stns[i]=pet1stn.loc[pet1stns[i].index[0]:pet1stns[i].index[-1]]
                for i in range(len(pbtv1stns)):
                    pbtv1stns[i]=Detection(pbtv1stns[i])
                    pbtv1stns[i]=pbtv1stn.loc[pbtv1stns[i].index[0]:pbtv1stns[i].index[-1]]
                plt.subplot(221)
                plt.title("电流和1stn")
                plt.plot(pexcurrent)
                plt.plot(p1cstn,label='1stn')
                for i in range(len(pexcurrents)):
                    plt.plot(pexcurrents[i],'o')
                plt.legend()# 显示图例
                plt.subplot(222)
                plt.title("缸温和1stn")
                plt.plot(pet1stn)
                plt.plot(p1cstn,label='1stn')
                for i in range(len(pet1stns)):
                    for j in range(4):
                        pet1stnresult[i][j]=pet1stns[i].iloc[pet1stns[i].shape[0]//5*j:pet1stns[i].shape[0]//5*(j+1)]
                        pet1stnresult[i].append(pet1stnresult[i][j])
                    pet1stnresult[i][4]=pet1stns[i].iloc[pet1stns[i].shape[0]//5*4:pet1stns[i].shape[0]//5*(4+1)+pet1stns[i].shape[0]%5]
                    for j in range(5):
                        plt.plot(pet1stnresult[i][j],'o')
                plt.legend()# 显示图例
                plt.subplot(223)
                plt.title("进气温度和1stn")
                plt.plot(piat1stn)
                plt.plot(p1cstn,label='1stn')
                for i in range(len(piat1stns)): 
                    for j in range(4):
                        piat1stnresult[i][j]=piat1stns[i].iloc[piat1stns[i].shape[0]//5*j:piat1stns[i].shape[0]//5*(j+1)]
                        piat1stnresult[i].append(piat1stnresult[i][j])
                    piat1stnresult[i][4]=piat1stns[i].iloc[piat1stns[i].shape[0]//5*4:piat1stns[i].shape[0]//5*(4+1)+piat1stns[i].shape[0]%5]
                    for j in range(5):
                        plt.plot(piat1stnresult[i][j],'o')
                plt.legend()# 显示图例
                plt.subplot(224)
                plt.title("电池电压和1stn")
                plt.plot(pbtv1stn)
                plt.plot(p1cstn,label='1stn')
                for i in range(len(pbtv1stns)):
                    for j in range(4):
                        pbtv1stnresult[i][j]=pbtv1stns[i].iloc[pbtv1stns[i].shape[0]//5*j:pbtv1stns[i].shape[0]//5*(j+1)]
                        pbtv1stnresult[i].append(pbtv1stnresult[i][j])
                    pbtv1stnresult[i][4]=pbtv1stns[i].iloc[pbtv1stns[i].shape[0]//5*4:pbtv1stns[i].shape[0]//5*(4+1)+pbtv1stns[i].shape[0]%5]
                    for j in range(5):
                        plt.plot(pbtv1stnresult[i][j],'o')
                plt.legend()# 显示图例
                
                l10=['分析'+path+'文件的缸温数据：']
                l20=['分析'+path+'文件的进气温度数据：']
                l30=['分析'+path+'文件的电池电压数据：']
                ps=['空载时','25%功率点时','50%功率点时','75%功率点时','100%功率点时','75%功率点时','50%功率点时','25%功率点时','空载时']
                for i in range(len(pexcurrents)):                
                    l1='{0}缸温Pet（℃）在20%时间节点的温度是{1}，在40%时间节点的温度是{2}，在60%时间节点的温度是{3}，在80%时间节点的温度是{4}，在100%时间节点的温度是{5}'.format(ps[i],pet1stnresult[i][0].iloc[-1].round(2),pet1stnresult[i][1].iloc[-1].round(2),pet1stnresult[i][2].iloc[-1].round(2),pet1stnresult[i][3].iloc[-1].round(2),pet1stnresult[i][4].iloc[-1].round(2))
                    l10.append(l1)
                    l2='{0}进气温度Piat（℃）在20%时间节点的温度是{1}，在40%时间节点的温度是{2}，在60%时间节点的温度是{3}，在80%时间节点的温度是{4}，在100%时间节点的温度是{5}'.format(ps[i],piat1stnresult[i][0].iloc[-1].round(2),piat1stnresult[i][1].iloc[-1].round(2),piat1stnresult[i][2].iloc[-1].round(2),piat1stnresult[i][3].iloc[-1].round(2),piat1stnresult[i][4].iloc[-1].round(2))
                    l20.append(l2)
                    l3='{0}电池电压Pbtv（V）在20%时间节点的电压是{1}，在40%时间节点的电压是{2}，在60%时间节点的电压是{3}，在80%时间节点的电压是{4}，在100%时间节点的电压是{5}'.format(ps[i],pbtv1stnresult[i][0].iloc[-1].round(2),pbtv1stnresult[i][1].iloc[-1].round(2),pbtv1stnresult[i][2].iloc[-1].round(2),pbtv1stnresult[i][3].iloc[-1].round(2),pbtv1stnresult[i][4].iloc[-1].round(2))
                    l30.append(l3)                
            except Exception as e:
                print('\n','>>>' * 20)
                print(traceback.format_exc())
                pass
            plt.tight_layout()
            plt.show()
            return l10,l20,l30
        if a==3:
            try:
                # 1stn到最后
                p1cstn=dfx['P1cstn']# 1stn
                p2cstn=dfx['P2cstn']# 2stn
                for i in range(len(p2cstn)):
                    if p2cstn.iloc[i]==1:                        
                        p2cstn1=p2cstn.iloc[i:]# 2stn开始置1
                        while p1cstn.iloc[i]==1:
                            i=i-1
                        p1cstn1=p1cstn.iloc[i+1:]# 1stn开始置1
                        break
                # plt.subplot(221)
                plt.title("1stn和2stn")
                plt.plot(p1cstn,label='1stn')
                plt.plot(p2cstn,label='2stn')
                plt.plot(p1cstn1,'^',label='1stn开始置1')
                plt.plot(p2cstn1,'v',label='2stn开始置1')
                plt.legend()# 显示图例
                
                l10=['分析'+path+'文件的全过程正时状态：']
                if all(p1cstn1 == 1) and all(p2cstn1 == 1):
                    l1='全过程正时状态：OK'
                else:
                    l1='全过程正时状态：NG'
                l10.append(l1)
            except Exception as e:
                print('\n','>>>' * 20)
                print(traceback.format_exc())
                pass
            plt.tight_layout()# 布局调整器，能够自动调整子图参数，使之填充整个图像区域且避免重叠。
            plt.show()
            return l10
    except Exception as e:
        print('\n','>>>' * 20)
        print(traceback.format_exc())
        pass
# %%
# mdf_file_path = 'C:/Users/Public/ECU-T001-T010/通机ECU阀体整机测试验证_ECUT007-新开模/新开模阀体_通机ECU阀体整机测试验证_2024.6.25_ECUT007_P2-3_P3_P4_P5.dat'
# mdf_file_path = 'C:/Users/Public/ECU-T001-T010/通机ECU阀体整机测试验证_ECUT003-新开模/新开模阀体_通机ECU阀体整机测试验证_2024.7.6_ECUT003_P2-3_P3-P4-P5.dat'
# mdf_file_path = 'C:/Users/Public/ECU-T001-T010/通机ECU阀体整机测试验证_ECUT003-新开模/新开模阀体_通机ECU阀体整机测试验证_2024.6.25_ECUT003_P2-3_P3_P4_P5.dat'
# mdf_file_path = 'C:/Users/Public/ECU-T001-T010/通机ECU阀体整机测试验证_ECUT005-新开模/新开模阀体_通机ECU阀体整机测试验证_2024.6.25_ECUT005_P2-3_P3_P4_P5.dat'
# a=3
# print(inca(mdf_file_path,a))